<template>
	<view class="content">
		<u-form :model="form" :error-type="['toast', 'message']" :rules="rules" ref="form">
			<u-form-item prop="username" label="账号"><u-input v-model="form.username" /></u-form-item>
			<u-form-item prop="password" label="密码"><u-input type="password" v-model="form.password" /></u-form-item>
			<view class="errorMsg-box">{{ errorMsg }}</view>
			<u-button type="default" @click="loginValidate">登录</u-button>
		</u-form>
		<template v-if="hasProvider">
			<u-divider margin-top="20" margin-bottom="20">建议使用{{ providerList[0].title }}登录</u-divider>
			<template v-for="provider in providerList">
				<u-button v-if="provider.key == 'weixin'" type="success" :key="provider.key" open-type="getUserInfo" @getuserinfo="wxGetUserInfo">
					<u-icon name="weixin-fill"></u-icon>
					<text style="margin-left: 5rpx;">{{ provider.title }}一键登录</text>
				</u-button>
				<u-button type="success" :key="provider.key" v-else>
					<text style="margin-left: 5rpx;">{{ provider.title }}一键登录</text>
				</u-button>
			</template>
		</template>
	</view>
</template>

<script>
import { mapState, mapMutations } from 'vuex';

import { setAppletInfo, getAppletInfo } from '@/utils/auth';
export default {
	components: {},
	data() {
		// 自定义验证函数
		const validator = (rule, value, callback) => {
			// 上面有说，返回true表示校验通过，返回false表示不通过
			// this.$u.test.isEmpty()就是返回true或者false的
			if (this.$u.test.isEmpty(value)) {
				this.errorMsg = rule.message;
				return false;
			}
			return true;
		};

		return {
			providerList: [],
			hasProvider: false,
			form: {
				username: '',
				password: ''
			},
			rules: {
				username: [
					{
						required: true,
						message: '账号不能为空'
						// validator
					}
				],
				password: [
					{
						required: true,
						message: '密码不能为空'
						// validator
					}
				]
			},
			errorMsg: ''
		};
	},
	methods: {
		/**
		 * 检测小程序运行平台
		 */
		initProvider() {
			const filters = [
				{
					key: 'weixin',
					title: '微信'
				},
				{
					key: 'qq',
					title: 'QQ'
				},
				{
					key: 'sinaweibo',
					title: '新浪微博'
				}
			];
			uni.getProvider({
				service: 'oauth',
				success: res => {
					if (res.provider && res.provider.length) {
						for (let i = 0; i < res.provider.length; i++) {
							if (filters.some(provider => provider.key == res.provider[i])) {
								this.providerList.push(filters[i]);
							}
						}
						this.hasProvider = true;
					}
				},
				fail: err => {
					console.error('获取服务供应商失败：' + JSON.stringify(err));
				}
			});
		},
		loginValidate() {
			this.$refs.form.validate(async (valid, errArr) => {
				if (!valid) {
					return;
				}
				this.loginHandler();
			});
		},
		async loginHandler() {
			try {
				await this.$store.dispatch('user/login', {
					username: this.form.username,
					password: this.form.password
				});
				this.$common.showToast({
					msg: '登录成功',
					success() {
						uni.reLaunch({
							url: '/pages/index/index'
						});
					}
				});
			} catch (e) {
				//TODO handle the exception
				this.$common.showToast(e.errorMessage);
			}
		},
		// 微信登录
		async wxGetUserInfo(infoRes) {
			if (!infoRes.detail.userInfo) {
				this.$common.showToast('您已拒绝授权');
				return;
			}
			try {
				let userInfo = infoRes.detail.userInfo;
				console.log(infoRes);
				let result = await this.$store.dispatch('user/login', {
					username: userInfo.nickName,
					pwd: 'asdsad',
					type: 1 // 0 默认登录  1 微信登录
				});
				setAppletInfo(userInfo);
				this.$common.showToast({
					msg: result.msg,
					success() {
						uni.reLaunch({
							url: '/pages/index/index'
						});
					}
				});
			} catch (e) {
				//TODO handle the exception
				this.$common.showToast(e.errorMessage);
			}
		}
	},
	onLoad() {
		this.initProvider();
	},
	// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
	onReady() {
		this.$refs.form.setRules(this.rules);
	}
};
</script>

<style lang="scss" scoped>
.content {
	padding: 20rpx;
}
.errorMsg-box {
	color: $u-type-error;
	margin: 20rpx 0rpx;
}
</style>
